package cn.devzyh.oms.coms.order.service;

import cn.devzyh.oms.common.core.message.ComsErrorCodes;
import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.coms.api.order.dto.OrderDTO;
import cn.devzyh.oms.coms.api.order.entity.OrderDetail;
import cn.devzyh.oms.coms.api.order.entity.OrderHeader;
import cn.devzyh.oms.coms.flow.context.FlowContext;
import cn.devzyh.oms.coms.flow.executor.FlowNode;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 检查单据工作流节点
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CheckOrderNode implements FlowNode {

	private final OrderService orderService;

	private static final String ORDER_ID = "orderId";

	@Override
	public R process(FlowContext ctx) {
		Long orderId = Long.parseLong(ctx.getParam(ORDER_ID).toString());
		OrderDTO order = orderService.getOrder(orderId);
		if (order == null) {
			return R.failedMessage(ComsErrorCodes.ORDER_NOT_EXISTS, orderId.toString());
		}

		OrderHeader header = order.getHeader();
		if (StrUtil.isBlank(header.getReceiveAddress())) {
			return R.failedMessage(ComsErrorCodes.RECEIVE_NOT_EXISTS, orderId.toString());
		}

		List<OrderDetail> details = order.getDetails();
		for (OrderDetail detail : details) {
			if (StrUtil.isBlank(detail.getSkuCode())) {
				return R.failedMessage(ComsErrorCodes.SKU_NOT_EXISTS, orderId.toString());
			}
		}

		// 设置缓存
		ctx.setMainCache(order);

		return R.ok();
	}

}
